package com.softbank.bsdiff;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.softbank.bsdiff.databinding.ActivityMainBinding;

import java.io.File;

public class MainActivity extends AppCompatActivity {


    private static final String TAG = "mytag";
    private ActivityMainBinding binding;
    private DownloadManager downloadManager;
    private long olderApkFileHandle, newApkFileHandle;

    private File fileOrigin, fileOut, filePatch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Example of a call to a native method
        TextView tv = binding.sampleText;

        File parent = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            parent = getCacheDir();
            fileOrigin = new File(parent.getPath() + "/origin.apk");
            fileOut = new File(parent.getPath() + "/patched.apk");
            filePatch = new File(parent.getPath() + "/patch.patch");
            Log.e(TAG, "onCreate: " + parent.getPath());
            if (fileOrigin.exists()) {
                toast("存在即为合理");
            }
            if (fileOut.exists()) {
                fileOut.delete();
            }
            judePatchFile();
        }


//        if (filePatch.exists()) {
//            filePatch.delete();
//        }
//        olderApkFileHandle = DownloadUtils.startDownload("老版本下载", "老版本下载中", "http://119.3.181.153:35004/download/android/app/debug/origin.apk", fileOrigin, downloadManager);
//        newApkFileHandle = DownloadUtils.startDownload("patch下载中", "patch下载中", "http://119.3.181.153:35004/download/android/app/debug/patch.patch", filePatch, downloadManager);

//        XXPermissions.with(this)
//                // 申请安装包权限
//                .permission(Permission.REQUEST_INSTALL_PACKAGES)
//                // 申请悬浮窗权限
//                //.permission(Permission.SYSTEM_ALERT_WINDOW)
//                // 申请通知栏权限
//                //.permission(Permission.NOTIFICATION_SERVICE)
//                // 申请系统设置权限
//                //.permission(Permission.WRITE_SETTINGS)
//                // 申请单个权限
////                .permission(Permission.RECORD_AUDIO)
//                // 申请多个权限
////                .permission(Permission.Group.CALENDAR)
//                .permission(Permission.Group.STORAGE)
//                .request(new OnPermissionCallback() {
//
//                    @Override
//                    public void onGranted(List<String> permissions, boolean all) {
//                        if (all) {
//                            toast("获取录音和日历权限成功");
//                                                    } else {
//                            toast("获取部分权限成功，但部分权限未正常授予");
//                        }
//                    }
//
//                    @Override
//                    public void onDenied(List<String> permissions, boolean never) {
//                        if (never) {
//                            toast("被永久拒绝授权，请手动授予录音和日历权限");
//                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
//                            XXPermissions.startPermissionActivity(MainActivity.this, permissions);
//                        } else {
//                            toast("获取录音和日历权限失败");
//                        }
//                    }
//                });

        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    }

    private void toast(String value) {
        Toast.makeText(this, value, Toast.LENGTH_LONG).show();
    }

    //广播监听下载的各个状态
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkOldApkStatus();
            checkPatchStatus();
        }
    };

    //检查下载状态
    private void checkOldApkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(olderApkFileHandle);
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成
                    cursor.close();
                    olderApkFileHandle = -1;
                    toast("Origin Apk下载完成");
                    judePatchFile();
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    cursor.close();
                    break;
            }
        }
    }

    private void checkPatchStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(newApkFileHandle);
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成
                    cursor.close();
                    toast("Patch下载完成");
                    newApkFileHandle = -1;
                    judePatchFile();
//
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    cursor.close();
                    break;
            }
        }
    }

    private void judePatchFile() {
        if (newApkFileHandle == -1 && olderApkFileHandle == -1 || true) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    BSDiffPatch diffPatch = new BSDiffPatch();
                    diffPatch.patchApk(fileOrigin.getPath(), fileOut.getPath(), filePatch.getPath());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toast("合并成功");
                        }
                    });
                }
            }).start();
        }
    }
}